using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MBLocale;

/// <summary>
/// Summary description for BindControl
/// </summary>
public class BindControl
{
    HDDatabase HDD = new HDDatabase();
    security objSec = new security();
    string strValCol = "";
    string SearchValue = "";
    byte bInclude_Empty_Value = 1;
    bool isDDE = false;
    string strDisFieldDataType = "";
	public BindControl()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public bool Bind(string strBindRowID, DropDownList ddlObj,ref DataTable dtBind,DataRow drpgctr)
    {
        try
        {
            if (drpgctr != null)
                if (drpgctr["control_html"].ToString().ToUpper() == "DDE")
                    isDDE = true;
            bool blnStatus = true;
            string strBindSql = GetBindSql(strBindRowID);
            //DataTable dtaObj = HDD.GetDataTable(strBindSql,true);
            DataTable dtaObj = HDD.GetDataTable(strBindSql);

            //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
            //CommonFunctions.decodeData(dtaObj);
            HandleLocalizedBindText(dtaObj, strBindRowID); // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
            ddlObj.DataSource = dtaObj;
            ddlObj.DataTextField = "Fld";
            ddlObj.DataValueField = "Val";
            ddlObj.DataBind();
            dtBind = dtaObj;
            if (bInclude_Empty_Value == 1)
                dtBind.ExtendedProperties.Add("IncludeEmpty", true);
            if (bInclude_Empty_Value == 1)
                ddlObj.Items.Insert(0,""); 
            // <DAVAMANI removed the loadvalue method and binded directly with data source>
            //LoadValues(dtaObj, ddlObj);

            if (isDDE)
                AddDropDownExtendedItems(ref ddlObj,strBindRowID);
            return blnStatus;
        }
        catch (Exception e1)
        {
            string s = e1.ToString();
            return false;
        }
    }
    
    public string GetBindSql(string strBindRowID)
    {
        string strBindSql = "";
        string strSql = "select * from sy_bnd where af_row_id = '" + strBindRowID.Replace("'","''") + "'";
        string strFldCol ="";
        string strValCol ="";
        string strTableName ="";
        string strWhCond = "";
        string additionalFields = "";
        string sRowLevelSecurity = "";
        string sTableName = "";
        string sBindafrowid = "";
        bool isSecurityApplied = false;
        DataTable dtaObj = HDD.GetDataTable(strSql);
        if (dtaObj.Rows.Count > 0)
        {
            sBindafrowid = dtaObj.Rows[0]["af_row_id"].ToString();
            isSecurityApplied = Convert2Boolean(dtaObj.Rows[0]["is_security_applied"].ToString());
            strFldCol = dtaObj.Rows[0]["bind_text"].ToString();
            strValCol = dtaObj.Rows[0]["bind_value"].ToString();
            strTableName = dtaObj.Rows[0]["bind_table"].ToString();
            strWhCond = dtaObj.Rows[0]["bind_parameter"].ToString();
            //strDisFieldDataType = GetDataType(strBindRowID, strFldCol);
            if (dtaObj.Columns.Contains("additional_fields")) additionalFields = dtaObj.Rows[0]["additional_fields"].ToString().Trim();
            if (dtaObj.Columns.Contains("include_empty_value"))
                if (dtaObj.Rows[0]["include_empty_value"] != System.DBNull.Value)
                    bInclude_Empty_Value = Convert.ToByte(dtaObj.Rows[0]["include_empty_value"]);
                else
                    bInclude_Empty_Value = 1;
            else
                bInclude_Empty_Value = 1;

            if (strFldCol == "")
            {
                strFldCol = strValCol;
            }
            sTableName = strTableName;
            if (strTableName.IndexOf(",") < 0)
            {
                strTableName = "[" + strTableName + "]";
            }

            
            if (additionalFields.Trim().Length > 0) additionalFields = "," + additionalFields;
            if (isDDE)//Added by srivatsan for DDE changes
            {
                string recordcount = HDD.GetColumnValue("select mem_value2 from sy_acr_mem where af_row_id = 'b57e98c8f2ebcb49'");
                if (recordcount.Trim() != "")
                    strBindSql = "select Top "+recordcount+" " + strFldCol + " as Fld, " + strValCol + " as Val " + additionalFields + " from " + strTableName.Replace("'", "''") + "";
            }
            else
            {
                strBindSql = "select " + strFldCol + " as Fld, " + strValCol + " as Val " + additionalFields + " from " + strTableName.Replace("'", "''") + "";
            }
            sRowLevelSecurity = objSec.getRowLevelSecurityData(sTableName, sTableName);
            if (strWhCond != "")    
            {
                DataTable dt_TempPara = HDD.GetDataTable(strBindSql + " where " + strWhCond); // Added by 'Imran Gani' on 19-Mar-2014, for bind where key handling
                if (dt_TempPara == null || dt_TempPara.Columns.Count == 0)
                    strBindSql += " " + strWhCond;
                else
                    strBindSql += " where " + strWhCond;
            }
            else
            {
                strBindSql += " where 1=1";
            }

            if (HttpContext.Current.Request.QueryString["PK"] != null && HttpContext.Current.Request.QueryString["pgs_id"].ToString() != "8c2cb032c3b3516d") // ps_user // Modified by 'Imran Gani' on 25-Nov-2013, to check pagaset_id for user page.
            {
                if (strTableName.ToLower().Contains(","))
                {
                    string orderTableName = GetTableName(strTableName);
                    strBindSql += " and " + orderTableName + ".af_row_id != '" + HttpContext.Current.Request.QueryString["PK"] + "'";
                }
                else
                {
                    strBindSql += " and af_row_id != '" + HttpContext.Current.Request.QueryString["PK"] + "'";
                }
            }

            if (sRowLevelSecurity != "")
                strBindSql += " and " + sRowLevelSecurity;

            if (isSecurityApplied) // Added by srivatsan. Check if security can be applied to the bind
            {
                strBindSql = getCustodianfilter(strBindSql, sBindafrowid,strTableName);
            }

            if (isDDE)
                strBindSql += " order by modified_at desc;";
            else
                strBindSql += " order by fld;";
        }
        return strBindSql;
    }

    /// <summary>
    ///  This function applies security based on the parameter.
    /// It does not look for the "is security applied" flag specified in sy_bnd.
    /// </summary>
    /// <param name="strBindRowID"></param>//Bind id//
    /// <param name="isSecApplied"></param>//true if security should be applied. False if not//
    /// <returns></returns>
    public string GetBindSql(string strBindRowID,bool isSecApplied)
    {
        string strBindSql = "";
        string strSql = "select * from sy_bnd where af_row_id = '" + strBindRowID.Replace("'", "''") + "';";
        string strFldCol = "";
        string strValCol = "";
        string strTableName = "";
        string strWhCond = "";
        string additionalFields = "";
        string sRowLevelSecurity = "";
        string sTableName = "";
        string sBindafrowid = "";
        bool isSecurityApplied = false;
        DataTable dtaObj = HDD.GetDataTable(strSql);
        if (dtaObj.Rows.Count > 0)
        {
            sBindafrowid = dtaObj.Rows[0]["af_row_id"].ToString();
            isSecurityApplied = Convert2Boolean(dtaObj.Rows[0]["is_security_applied"].ToString());
            strFldCol = dtaObj.Rows[0]["bind_text"].ToString();
            strValCol = dtaObj.Rows[0]["bind_value"].ToString();
            strTableName = dtaObj.Rows[0]["bind_table"].ToString();
            strWhCond = dtaObj.Rows[0]["bind_parameter"].ToString();
            if (dtaObj.Columns.Contains("additional_fields")) additionalFields = dtaObj.Rows[0]["additional_fields"].ToString().Trim();
            if (dtaObj.Columns.Contains("include_empty_value"))
                if (dtaObj.Rows[0]["include_empty_value"] != System.DBNull.Value)
                    bInclude_Empty_Value = Convert.ToByte(dtaObj.Rows[0]["include_empty_value"]);
                else
                    bInclude_Empty_Value = 1;
            else
                bInclude_Empty_Value = 1;

            if (strFldCol == "")
            {
                strFldCol = strValCol;
            }
            sTableName = strTableName;
            if (strTableName.IndexOf(",") < 0)
            {
                strTableName = "[" + strTableName + "]";
            }
            if (additionalFields.Trim().Length > 0) additionalFields = "," + additionalFields;
            if (isDDE)//Added by srivatsan for DDE changes
            {
                string recordcount = HDD.GetColumnValue("select mem_value2 from sy_acr_mem where af_row_id = 'b57e98c8f2ebcb49'");
                if (recordcount.Trim() != "")
                    strBindSql = "select Top " + recordcount + " " + strFldCol + " as Fld, " + strValCol + " as Val " + additionalFields + " from " + strTableName.Replace("'", "''") + "";
            }
            else
            {
                strBindSql = "select " + strFldCol + " as Fld, " + strValCol + " as Val " + additionalFields + " from " + strTableName.Replace("'", "''") + "";
            }
            sRowLevelSecurity = objSec.getRowLevelSecurityData(sTableName, sTableName);
            if (strWhCond != "")
            {
                DataTable dt_TempPara = HDD.GetDataTable(strBindSql + " where " + strWhCond); // Added by 'Imran Gani' on 19-Mar-2014, for bind where key handling
                if (dt_TempPara == null || dt_TempPara.Columns.Count == 0)
                    strBindSql += " " + strWhCond;
                else
                    strBindSql += " where " + strWhCond;
            }
            else
            {
                strBindSql += " where 1=1";
            }

            if (HttpContext.Current.Request.QueryString["PK"] != null && HttpContext.Current.Request.QueryString["pgs_id"].ToString() != "8c2cb032c3b3516d") // ps_user // Modified by 'Imran Gani' on 25-Nov-2013, to check pagaset_id for user page.
            {
                if (strTableName.ToLower().Contains(","))
                {
                    string orderTableName = GetTableName(strTableName);
                    strBindSql += " and " + orderTableName + ".af_row_id != '" + HttpContext.Current.Request.QueryString["PK"] + "'";
                }
                else
                {
                    strBindSql += " and af_row_id != '" + HttpContext.Current.Request.QueryString["PK"] + "'";
                }
            }

            if (sRowLevelSecurity != "")
                strBindSql += " and " + sRowLevelSecurity;

            if (isSecApplied) // Added by srivatsan. Check if security can be applied to the bind
            {
                strBindSql = getCustodianfilter(strBindSql, sBindafrowid,strTableName);
            }
            if (isDDE)
                strBindSql += " order by modified_at desc";
            else
                strBindSql += " order by fld";
        }
        return strBindSql;
    }

    public string GetBindSql_forValue(string strBindRowID)
    {
        string strBindSql = "";
        string strSql = "select * from sy_bnd where af_row_id = '" + strBindRowID.Replace("'", "''") + "';";
        string strFldCol = "";
        string strValCol = "";
        string strTableName = "";
        string strWhCond = "";
        DataTable dtaObj = HDD.GetDataTable(strSql);
        if (dtaObj.Rows.Count > 0)
        {
            strFldCol = dtaObj.Rows[0]["bind_text"].ToString();
            strValCol = dtaObj.Rows[0]["bind_value"].ToString();
            this.strValCol = strValCol; //added for building where condition in getbindvalue method 
            strTableName = dtaObj.Rows[0]["bind_table"].ToString();
            strWhCond = dtaObj.Rows[0]["bind_parameter"].ToString();

            //if (strWhCond != "")
            //{
            //    strWhCond = strWhCond + " and ";//strWhCond += strWhCond + " and ";
            //}
            
            if (strFldCol == "")
            {
                strFldCol = strValCol;
            }
            //strBindSql = "select " + strFldCol + " " + " from [" + strTableName.Replace("'", "''") + "] where " + strWhCond.Replace("'", "''") + " [" + strValCol + "] = ";
            // Added by 'Imran Gani' on 19-Mar-2014, for bind where key handling
            strBindSql = "select " + strFldCol + " " + " from [" + strTableName.Replace("'", "''") + "]";
            if (strWhCond != "")
            {
                DataTable dt_TempPara = HDD.GetDataTable(strBindSql + " where " + strWhCond.Replace("'", "''"));
                if (dt_TempPara == null || dt_TempPara.Columns.Count == 0)
                    strBindSql = strBindSql + " " + strWhCond.Replace("'", "''") + " and [" + strValCol + "] = ";
                else
                    strBindSql = strBindSql + " where " + strWhCond.Replace("'", "''") + " and [" + strValCol + "] = ";
            }
            else
                strBindSql += " where [" + strValCol + "] = ";
        }
        return strBindSql;
    }

    private bool LoadValues(DataTable dtaObj, DropDownList ddlObj)
    {
        bool blnStatus = true;
        ddlObj.Items.Clear();
        ddlObj.Items.Add(new ListItem("Select", ""));
        string strValCol = "";
        string strFldCol = "";
        for (int i = 0; i < dtaObj.Rows.Count; i++)
        {
            strFldCol = dtaObj.Rows[i]["Val"].ToString();
            strValCol = dtaObj.Rows[i]["Fld"].ToString();
            ddlObj.Items.Add(new ListItem(strFldCol, strValCol));
        }
        return blnStatus;
    }
    /// <summary>
    /// This function will get the bind sql based on the search value given in the parameter.
    /// </summary>
    /// <param name="strBindRowID">Bind ID</param>
    /// <param name="searchvalue">Value to be searched (can also be empty to return all values)</param>
    /// <param name="basedonvalue"></param>
    /// <returns></returns>
    public string GetSearchSQLBySearchValue(string strBindRowID,string searchvalue,bool basedonvalue,bool bUseLike,string limitQry)
    {
        string strBindSql = "";
        string straddfields = "";
        try
        {

            SearchValue = searchvalue;
                    string strSql = "select * from sy_bnd where af_row_id = '" + strBindRowID.Replace("'", "''") + "';";
                    string strFldCol = "";
                    string strValCol = "";
                    string strTableName = "";
                    string strWhCond = "";
                    string additionalFields = "";
                    string sRowLevelSecurity = "";
                    string sTableName = "";
                    string sBindafrowid = "";
                    bool isSecurityApplied = false;

                    DataTable dtaObj = HDD.GetDataTable(strSql);
                    if (dtaObj.Rows.Count > 0)
                    {
                        isSecurityApplied = Convert2Boolean(dtaObj.Rows[0]["is_security_applied"].ToString());
                        sBindafrowid = dtaObj.Rows[0]["af_row_id"].ToString();
                        strFldCol = dtaObj.Rows[0]["bind_text"].ToString();
                        strValCol = dtaObj.Rows[0]["bind_value"].ToString();
                        strTableName = dtaObj.Rows[0]["bind_table"].ToString();

                        strWhCond = dtaObj.Rows[0]["bind_parameter"].ToString();
                        if (dtaObj.Columns.Contains("additional_fields")) additionalFields = dtaObj.Rows[0]["additional_fields"].ToString().Trim();
                        if (dtaObj.Columns.Contains("include_empty_value"))
                            if (dtaObj.Rows[0]["include_empty_value"] != System.DBNull.Value)
                                bInclude_Empty_Value = Convert.ToByte(dtaObj.Rows[0]["include_empty_value"]);
                            else
                                bInclude_Empty_Value = 1;
                        else
                            bInclude_Empty_Value = 1;

                        if (strFldCol == "")
                        {
                            strFldCol = strValCol;
                        }
                        sTableName = strTableName;
                        if (strTableName.IndexOf(",") < 0)
                        {
                            strTableName = "[" + strTableName + "]";
                        }
                        if (additionalFields.Trim().Length > 0) additionalFields = "," + additionalFields;


                        // Srivatsan
                        straddfields = additionalFields;
                        //additionalFields = strValCol + "," + strFldCol + "," + additionalFields;
                        //additionalFields = strFldCol + "," + additionalFields;
                        string[] arradditionalfields = additionalFields.Split(',');
                        string stradditionalfields = "";
                        for (int i = 0; i < arradditionalfields.Length; i++)
                        {
                            if (arradditionalfields[i] != "")
                            {
                                stradditionalfields = stradditionalfields + "'" + arradditionalfields[i].Replace("'","''") + "',";
                                
                            }
                        }
                        if (stradditionalfields.Length > 0)
                        {
                            stradditionalfields = stradditionalfields.Substring(0, stradditionalfields.Length - 1);
                        }
                        string sqlgetcontrolnames = "select A.af_row_id,A.page_id,B.control_id,B.control_attrib_id,B.control_name from sy_pg A,sy_pg_ctr B where A.af_row_id = B.page_id and A.page_table_name = '" + sTableName + "' and control_id in(" + stradditionalfields + ")";
                        DataSet ds = HDD.GetDataset(sqlgetcontrolnames);

                        strBindSql = "select " + limitQry.Trim() + " " + strValCol + " as [Val]," + strFldCol + ",";

                        if (ds != null)
                        {
                            if (ds.Tables.Count > 0)
                            {
                                if (ds.Tables[0].Rows.Count > 0)
                                {
                                    

                                    foreach (DataRow dr in ds.Tables[0].Rows)
                                    {
                                        strBindSql += dr["control_attrib_id"].ToString() + " as [" + dr["control_name"].ToString() + "],";
                                    }                                  

                                }
                            }
                        }
                        strBindSql = strBindSql.Substring(0, strBindSql.Length - 1);

                        strBindSql += " from " + strTableName.Replace("'", "''") + "";

                        

                        //strBindSql = "select " + strFldCol + " as Fld, " + strValCol + " as Val " + additionalFields + " from " + strTableName.Replace("'", "''") + "";
                        sRowLevelSecurity = objSec.getRowLevelSecurityData(sTableName, sTableName);
                        if (strWhCond != "")
                        {
                            DataTable dt_TempPara = HDD.GetDataTable(strBindSql + " where " + strWhCond); // Added by 'Imran Gani' on 19-Mar-2014, for bind where key handling
                            if (dt_TempPara == null || dt_TempPara.Columns.Count == 0)
                                strBindSql += " " + strWhCond;
                            else
                                strBindSql += " where " + strWhCond;
                        }
                        else
                        {
                            strBindSql += " where 1=1";
                        }

                        if (HttpContext.Current.Request.QueryString["PK"] != null && HttpContext.Current.Request.QueryString["pgs_id"].ToString() != "8c2cb032c3b3516d") // ps_user // Modified by 'Imran Gani' on 25-Nov-2013, to check pagaset_id for user page.
                        {
                            if (strTableName.ToLower().Contains(","))
                            {
                                string orderTableName = GetTableName(strTableName);
                                strBindSql += " and " + orderTableName + ".af_row_id != '" + HttpContext.Current.Request.QueryString["PK"] + "'";
                            }
                            else
                            {
                                strBindSql += " and af_row_id != '" + HttpContext.Current.Request.QueryString["PK"] + "'";
                            }
                        }

                        if (sRowLevelSecurity != "")
                            strBindSql += " and " + sRowLevelSecurity;

                        if (basedonvalue)
                        {
                            if (searchvalue.Trim() != "")
                            {
                                searchvalue = searchvalue.Trim();
                                if (bUseLike)
                                {
                                    if (searchvalue.Contains("*"))
                                    {
                                        searchvalue = searchvalue.Replace("*", "%");
                                    }
                                    searchvalue = searchvalue.Replace("'", "''");
                                    strBindSql += " and " + strFldCol + " like '"+ (limitQry.Trim().Length>0 ? "" : "%") + searchvalue + "%'";//limitQry will be there for Typeahead only
                                }
                                else
                                {
                                    searchvalue = searchvalue.Replace("'", "''");
                                    strBindSql += " and " + strFldCol + "='" + searchvalue + "'";
                                }
                            }
                        }

                        if (isSecurityApplied) // Added by srivatsan. Check if security can be applied to the bind
                        {
                            strBindSql = getCustodianfilter(strBindSql, sBindafrowid,strTableName);
                        }

                        if (strFldCol.Contains("+"))
                        {
                            strBindSql += " order by " + strFldCol;
                        }
                        else
                        {
                            strBindSql += " order by "+ strTableName + "." + strFldCol;
                        }
                        
                    }
            
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetSearchSQLBySearchValue :"+ ex.Message);
        }
        return strBindSql;
    }

    private string getCustodianfilter(string sqlBindSQl, string bindaf_row_id, string strTableName) // Added by srivatsan
    {
        string result = "";
        string useraf_row_id="";
        string strcustodianfilter="";
        //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
        string str_OwnerId = "";
        string modelConString = "";
        string strpgs_id = HttpContext.Current.Request.QueryString["pgs_id"].ToString();
        modelConString = HttpContext.Current.Session["servercon"].ToString();
        if (HttpContext.Current.Session["dbcon"].ToString() != modelConString)
        {
            BusinessUnit.Access ACS = new BusinessUnit.Access(HttpContext.Current.Session["userid"].ToString(), HDD.GetConnection().ConnectionString, strpgs_id);
            str_OwnerId = ACS.AccessableOwners;
        }
        //----------------End for Org Security------------------
        if (HttpContext.Current.Session["user_afrowid"] != null)
        {
            useraf_row_id = HttpContext.Current.Session["user_afrowid"].ToString();
        }
        try
        {
            if (bindaf_row_id != "f496930dfe0b690f")  // This is to check if the bind is not for owner id field
            {
                if (HttpContext.Current.Session["user_afrowid"] != null)
                {
                    //-----------Added & commented by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                    sqlBindSQl += str_OwnerId + " or owner_id is null ";
                    //if (HttpContext.Current.Session["custodian"] != null)
                    //{
                    //    strcustodianfilter = HttpContext.Current.Session["custodian"].ToString();
                    //    if (strcustodianfilter != "")
                    //    {
                    //        if (useraf_row_id != "e51e0327224a2eb9")
                    //        {
                    //            if (strcustodianfilter.ToLower() != "ar")
                    //            {
                    //                //sqlBindSQl += " and owner_id in('" + useraf_row_id + "','e51e0327224a2eb9') ";
                    //                sqlBindSQl += " and (owner_id = '" + useraf_row_id + "' or owner_id is null) ";
                    //            }
                    //            else
                    //            {
                    //                //sqlBindSQl += " and (owner_id = '" + useraf_row_id + "' or owner_id is null and owner_id <> '" + "e51e0327224a2eb9" + "') ";
                    //                sqlBindSQl += " and (owner_id not in ('e51e0327224a2eb9') or (owner_id = '"+useraf_row_id+"' or owner_id is null))";
                    //            }
                    //        }
                    //    }
                    //}
                    //----------------End for Org Security------------------
                }
            }
            else
            {
              sqlBindSQl = GetCustodianFilterForOwner(sqlBindSQl,strTableName,SearchValue);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getCustodianfilter :" + ex.Message);
        }
        finally
        {

        }
        return sqlBindSQl;
    }

    private bool Convert2Boolean(string value)
    {
        bool result = false;
        
        try
        {
            if (value != "")
            {
                result = Convert.ToBoolean(value);
            }
        }
        catch
        {

        }
        return result;
    }

    private string ReplaceOwnerQuery(string sql)
    {
        try
        {
            if (sql != "")
            {
                string sqlunion = sql.Substring(0, sql.IndexOf("where"));

                sqlunion += " where af_row_id = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "' and owner_id is not null";

                sql = "(" + sql + ") union all (" + sqlunion + ")";
            }
        }
        catch
        {
        }

        return sql;

    }

    private string GetCustodianFilterForOwner(string strBindSQL, string strTableName, string sSearchValue)
    {
        if (strBindSQL != "")
        {
            if (HttpContext.Current.Session["roleid"] != null)
            {
                //if (HttpContext.Current.Session["roleid"].ToString() != "e7029dafbe379f85") // Checking if role is not afadmin
                //{
                //string sql = "select change_owner from sy_obj A, sy_obj_acc B where A.object_id = B.object_id and A.object_table ='"+strTableName+"' and B.role_id = '"+HttpContext.Current.Session["roleid"].ToString()+"'";
                //bool change_owner = Convert2Boolean(HDD.GetColumnValue(sql));
                security sec = new security();
                string strpgs_id = HttpContext.Current.Request.QueryString["pgs_id"].ToString();
                bool change_owner = sec.getRightsForMRUObjects(strpgs_id, "change_owner");
                sec = null;
                if (change_owner)
                {
                    // Added for owner field

                    #region Commented By 'Imran Gani' (copied from RakaTech - uma) on 05-June-2013 to apply Org Security for Owner

                    //if (HttpContext.Current.Session["roleid"].ToString() != "377e55cec8d53d7d" && HttpContext.Current.Session["roleid"].ToString() != "e7029dafbe379f85")
                    //{
                    //    if (HttpContext.Current.Session["custodian"] != null)
                    //    {
                    //        //if (HttpContext.Current.Session["custodian"].ToString() != "")
                    //        //{
                    //        if (HttpContext.Current.Session["custodian"].ToString() != "ar")
                    //        {
                    //            //sqlBindSQl += " or af_row_id ='" + HttpContext.Current.Session["user_afrowid"].ToString() + "' and (owner_id ='" + useraf_row_id + "' or owner_id is null)";
                    //            strBindSQL += " and (owner_id ='" + HttpContext.Current.Session["user_afrowid"].ToString() + "' or owner_id is null)";
                    //            if (sSearchValue.Trim() != "")
                    //            {
                    //                if (HttpContext.Current.Session["userid"].ToString().ToLower().Contains(sSearchValue.Trim().ToLower()))
                    //                {
                    //                    strBindSQL = ReplaceOwnerQuery(strBindSQL);
                    //                }
                    //            }
                    //            else
                    //            {
                    //                strBindSQL = ReplaceOwnerQuery(strBindSQL);
                    //            }
                    //        }
                    //        else
                    //        {
                    //            if (sSearchValue.Trim() != "")
                    //            {
                    //                //if (HttpContext.Current.Session["userid"].ToString().ToLower().Contains(sSearchValue.Trim().ToLower()))
                    //                //{
                    //                //    strBindSQL = ReplaceOwnerQuery(strBindSQL);
                    //                //}
                    //            }
                    //            else
                    //            {
                    //                //strBindSQL = ReplaceOwnerQuery(strBindSQL);
                    //            }
                    //        }
                    //        //}
                    //    }
                    //}
                    //else if (HttpContext.Current.Session["roleid"].ToString() == "377e55cec8d53d7d")
                    //{
                    //    if (HttpContext.Current.Session["custodian"] != null)
                    //    {
                    //        //if (HttpContext.Current.Session["custodian"].ToString() != "")
                    //        //{
                    //        if (HttpContext.Current.Session["custodian"].ToString() != "ar")
                    //        {
                    //            if (HttpContext.Current.Session["custodian"].ToString().Trim() != "")
                    //            {
                    //                strBindSQL += " and (owner_id ='" + HttpContext.Current.Session["user_afrowid"].ToString() + "' or owner_id is null)";
                    //                if (sSearchValue.Trim() != "")
                    //                {
                    //                    if (HttpContext.Current.Session["userid"].ToString().ToLower().Contains(sSearchValue.ToLower()))
                    //                    {
                    //                        strBindSQL = ReplaceOwnerQuery(strBindSQL);
                    //                    }
                    //                }
                    //                else
                    //                {
                    //                    strBindSQL = ReplaceOwnerQuery(strBindSQL);
                    //                }
                    //            }
                    //        }
                    //        else
                    //        {
                    //            if (HttpContext.Current.Request.QueryString["PK"] != null)
                    //            {
                    //                if (HttpContext.Current.Request.QueryString["PK"].ToString() == HttpContext.Current.Session["user_afrowid"].ToString())
                    //                {
                    //                    if (sSearchValue.Trim() != "")
                    //                    {
                    //                        if (HttpContext.Current.Session["userid"].ToString().ToLower().Contains(sSearchValue.ToLower()))
                    //                        {
                    //                            strBindSQL = ReplaceOwnerQuery(strBindSQL);
                    //                        }
                    //                    }
                    //                    else
                    //                    {
                    //                        strBindSQL = ReplaceOwnerQuery(strBindSQL);
                    //                    }
                    //                }
                    //            }
                    //        }
                    //        //}
                    //    }
                    //}
                    #endregion

                    string str_OwnerId = "";
                    string modelConString = "";

                    modelConString = HttpContext.Current.Session["servercon"].ToString();
                    if (HttpContext.Current.Session["dbcon"].ToString() != modelConString)
                    {
                        BusinessUnit.Access ACS = new BusinessUnit.Access(HttpContext.Current.Session["userid"].ToString(), HDD.GetConnection().ConnectionString, strpgs_id);
                        str_OwnerId = ACS.AccessableOwners;
                    }
                    if (HttpContext.Current.Session["roleid"].ToString() != "377e55cec8d53d7d" && HttpContext.Current.Session["roleid"].ToString() != "e7029dafbe379f85")
                    {
                        //sqlBindSQl += " or af_row_id ='" + HttpContext.Current.Session["user_afrowid"].ToString() + "' and (owner_id ='" + useraf_row_id + "' or owner_id is null)";
                        //strBindSQL += " and (owner_id ='" + HttpContext.Current.Session["user_afrowid"].ToString() + "' or owner_id is null)";
                        strBindSQL += str_OwnerId.Replace("owner_id", "af_row_id") + " or owner_id is null";
                    }
                    else if (HttpContext.Current.Session["roleid"].ToString() == "377e55cec8d53d7d")
                    {
                        strBindSQL += str_OwnerId.Replace("owner_id", "af_row_id") + " or owner_id is null";
                        if (HttpContext.Current.Request.QueryString["PK"] != null)
                        {
                            if (HttpContext.Current.Request.QueryString["PK"].ToString() == HttpContext.Current.Session["user_afrowid"].ToString())
                            {
                                if (sSearchValue.Trim() != "")
                                {
                                    if (HttpContext.Current.Session["userid"].ToString().ToLower().Contains(sSearchValue.ToLower()))
                                    {
                                        strBindSQL = ReplaceOwnerQuery(strBindSQL);
                                    }
                                }
                                else
                                {
                                    strBindSQL = ReplaceOwnerQuery(strBindSQL);
                                }
                            }
                        }
                    }
                    else if (HttpContext.Current.Session["roleid"].ToString() == "e7029dafbe379f85")
                    {
                        if (HttpContext.Current.Request.QueryString["PK"] != null)
                        {
                            if (HttpContext.Current.Request.QueryString["PK"].ToString() == HttpContext.Current.Session["user_afrowid"].ToString())
                            {
                                if (sSearchValue.Trim() != "")
                                {
                                    if (HttpContext.Current.Session["userid"].ToString().ToLower().Contains(sSearchValue.ToLower()))
                                    {
                                        strBindSQL = ReplaceOwnerQuery(strBindSQL);
                                    }
                                }
                                else
                                {
                                    strBindSQL = ReplaceOwnerQuery(strBindSQL);
                                }
                            }
                        }
                    }
                    // End
                }
                //}
            }
        }
        return strBindSQL;
    }
    private string GetTableName(string strtablename)
    {
        if (strtablename.Contains(","))
        {
            string[] splittable = strtablename.Split(',');
            if (splittable.Length > 0)
            {
                strtablename = splittable[0].ToString();
            }
        }
        return strtablename;
    }

    private void AddDropDownExtendedItems(ref DropDownList DDL, string strBindRowID)
    {
        ListItem listitem = null;
        try
        {
            DataTable dt = HDD.GetDataTable("select * from sy_acr_mem where acr_id = 'e72dc66101a78b18' order by mem_seq"); //Get default items for Drop down
            if (dt != null)
                if (dt.Rows.Count > 0)

                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["mem_value1"].ToString().Trim() != "")
                            if (dr["mem_value1"].ToString().Trim().ToLower() == "true")
                                switch (dr["mem_id"].ToString().ToUpper())
                                {
                                    case "ADD":
                                        if(GetRights(strBindRowID,"create"))
                                        {
                                            listitem = new ListItem(dr["mem_name"].ToString(), dr["mem_id"].ToString());
                                            DDL.Items.Add(listitem);
                                        }
                                        break;
                                    case "SRH":
                                        listitem = new ListItem(dr["mem_name"].ToString(), dr["mem_id"].ToString());
                                        DDL.Items.Add(listitem);
                                        break;
                                    case "TYP":
                                        listitem = new ListItem(dr["mem_name"].ToString(), dr["mem_id"].ToString());
                                        DDL.Items.Add(listitem);
                                        break;
                                    case "EDT":
                                        break;
                                }
                    }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddDropDownExtendedItems :" + ex.Message);
        }

    }
    /// <summary>
    /// This will return whether the current user has access to current bind object
    /// </summary>
    /// <param name="strBindRowID"></param>
    /// <param name="rights">Create/Delete/Edit</param>
    /// <returns></returns>
    public bool GetRights(string strBindRowID, string rights)
    {
        security sec = new security();
        HDDatabase hdd = new HDDatabase();
        bool status = false;
        try
        {
            //string object_id = hdd.GetColumnValue("select object_id from sy_pg where af_row_id = '" + page_id + "'");
            string object_id = HDD.GetColumnValue("select object_id from sy_obj A, sy_bnd B where A.object_table = B.bind_table and B.af_row_id = '" + strBindRowID + "'");
            status = sec.getObjectRightsForUser(object_id,rights);
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetRights :"+ ex.Message);
        }
        finally
        {
            sec= null;
            hdd = null;
        }
        return status;
    }
    private DataSet Removeafadminrecord(DataSet ds)
    {
        if(ds!=null)
        {
            if(ds.Tables.Count>0)
            {
                if(ds.Tables[0].Rows.Count>0)
                {
                    int removeindex =-1;
                    for(int i=0;i<ds.Tables[0].Rows.Count;i++)
                    {
                        if(ds.Tables[0].Rows[i]["val"].ToString()=="e51e0327224a2eb9")
                        {
                            removeindex = i;
                        }
                    }

                    if(removeindex>-1)
                    {
                        ds.Tables[0].Rows.RemoveAt(removeindex);
                        ds.AcceptChanges();
                    }



                }
            }

        }
        return ds;


    }
    private void removeUnwantedRecords(DataSet dsBind,string strBindafrowid)
    {
        if (HttpContext.Current.Session["user_afrowid"] != null)
        {
            //strBindafrowid = HDD.GetColumnValue("select af_row_id from sy_bnd where af_row_id = '" + strBindids + "'");
            if (HttpContext.Current.Session["user_afrowid"].ToString() != "e51e0327224a2eb9")
            {
                 
                if(strBindafrowid == "f496930dfe0b690f")
                {
                    dsBind =Removeafadminrecord(dsBind);    
                }
            }           
        }
    }
    public DataSet getBindData(string strBindRowID, bool isSearchByValue, string currentValue,out string displayValue, out string storageValue,string limitQry)
    {
        //string strstoragevalue = "";
        //string strdisplayvalue = "";
        displayValue = ""; storageValue = "";
        HDDatabase hdd = new HDDatabase();
        BindControl BC = new BindControl();
        DataSet ds = new DataSet();
        string bindafrowid="";
        try
        {

            string sqlbind = "select * from sy_bnd where af_row_id = '" + strBindRowID + "'";
            DataTable dtBind = hdd.GetDataTable(sqlbind);
            if (dtBind != null)
            {
                if (dtBind.Rows.Count > 0)
                {
                    DataRow[] drr = dtBind.Select();
                    bindafrowid = drr[0]["af_row_id"].ToString();
                    displayValue = drr[0]["bind_text"].ToString();
                    storageValue = drr[0]["bind_value"].ToString();
                }
            }

            string sql = "";
            if (isSearchByValue)
            {
                sql = BC.GetSearchSQLBySearchValue(strBindRowID, currentValue, true, true,limitQry);
            }
            else
            {
                //sql = BC.GetBindSQLforSearch(strBindRowID);
                sql = BC.GetSearchSQLBySearchValue(strBindRowID, currentValue, false, true,limitQry);
            }
            ds = hdd.GetDataset(sql);
            if (bindafrowid!="") removeUnwantedRecords(ds,bindafrowid);
            HandleLocalizedBindText(ds.Tables[0], strBindRowID); // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
            //foreach (DataColumn dc in ds.Tables[0].Columns)
            //{
            //    if (dc.ColumnName.Contains("@"))
            //    {
            //        string[] arrstorage = dc.ColumnName.Split('@');
            //        strstoragevalue = arrstorage[1].ToString();
            //        istoragefield = dc.Ordinal;
            //        ds.Tables[0].Columns[dc.ColumnName].ColumnName = strstoragevalue;
            //        ds.AcceptChanges();
            //    }
            //    if (dc.ColumnName.Contains("$"))
            //    {
            //        string[] arrdisplay = dc.ColumnName.Split('$');
            //        strdisplayvalue = arrdisplay[1].ToString();
            //        ds.Tables[0].Columns[dc.ColumnName].ColumnName = strdisplayvalue;
            //        ds.AcceptChanges();
            //    }


            //}


        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getBindData : " + ex.Message);
        }
        finally
        {
            hdd = null;
            BC = null;
        }
        return ds;

    }     
    #region DateTime fields in DDE
    ///// <summary>
    ///// This function will get the DataType of the field used in Bind
    ///// </summary>
    ///// <param name="bind_table">Bind ID of the Bind</param>
    ///// <param name="fieldname">name of the field for which datatype need to be found(displayfield/storagefield)</param>
    ///// <returns></returns>
    //public string GetDataType(string strBindRowID,string fieldname)
    //{
    //    string result = "TX";
    //    HDDatabase hdd = new HDDatabase();
    //    try
    //    {
    //        if (strBindRowID.Trim() != "")
    //            if (fieldname.Trim() != "")
    //            {
    //                string sql = "select attrib_data_type from sy_obj A, sy_obj_att B,sy_bnd C where A.af_row_id = B.object_id and B.attrib_id = '"+fieldname+"' and A.object_table = C.bind_table and C.af_row_id = '"+strBindRowID+"'";
    //                result = hdd.GetColumnValue(sql);
    //            }
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("Error : GetDataType :" + ex.Message);
    //    }
    //    finally
    //    {
    //        hdd = null;
    //    }
    //    return result;
    //}

    ////private DataSet ConvertValueBasedOnDataType(DataSet ds,string datatype)
    ////{
    ////    try
    ////    {
    ////        if(ds!= null)
    ////            if(ds.Tables.Count>0)
    ////                if (ds.Tables[0].Rows.Count > 0)
    ////                {
    ////                    if (datatype.ToUpper() == "DT")
    ////                    {
    ////                        foreach (DataRow drr in ds.Tables[0].Rows)
    ////                        {

    ////                        }
    ////                    }
    ////                }

    ////    }
    ////    catch(Exception ex)
    ////    {
    ////        LogWriter.WriteLog("Error : ConvertValueBasedOnDataType :"+ ex.Message);
    ////    }
    ////    return ds;

    ////}
    #endregion

    /// <summary>
    /// To handle the data type of a bind field. From numeric to locale formatted value.
    /// </summary>
    /// <param name="dtaObj">Datatable with bind values.</param>
    /// <param name="sDisplayField">Display field which should handle locale</param>
    // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
    public void HandleLocalizedBindText(DataTable dtaObj, string strBindRowID)
    {
        Localization loc = new Localization();
        try
        {
            DataRow dr_bind = HDD.GetTableRow("select * from sy_bnd where af_row_id = '" + strBindRowID + "';");
            if (dr_bind != null)
            {
                DataRow dr_pg_ctr = HDD.GetTableRow("select * from sy_pg_ctr where page_id = (select af_row_id from sy_pg where page_table_name = '" + dr_bind["bind_table"].ToString() + "') and control_id = '" + dr_bind["bind_text"].ToString() + "'");
                if (dr_pg_ctr != null)
                {
                    string sDisplayField = (dtaObj.Columns.Contains("fld") ? "fld" : dr_bind["bind_text"].ToString());
                    dtaObj = loc.getLocalizedColumns(dtaObj, dr_pg_ctr["control_attrib_type"].ToString(), sDisplayField);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : HandleLocalizedBindText : " + ex.Message);
        }
        finally
        {
            loc = null;
        }
    }
}

